package com.english_test_sys.service.Impl;

import com.english_test_sys.mapper.WrongQuestionMapper;
import com.english_test_sys.pojo.WrongQuestion;
import com.english_test_sys.service.WrongQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class WrongQuestionServiceImpl implements WrongQuestionService {

    @Autowired
    private WrongQuestionMapper wrongQuestionMapper;



    @Override
    public WrongQuestion addWrongQuestion(WrongQuestion wrongQuestion) {
        // 检查是否已经存在该错题记录
        WrongQuestion existing = wrongQuestionMapper.selectByUserIdAndQuestionId(
                wrongQuestion.getUserId(), wrongQuestion.getQuestionId());

        if (existing != null) {
            // 如果已存在，则增加错误次数
            existing.setWrongCount(existing.getWrongCount() + 1);
            wrongQuestionMapper.update(existing);
            return existing;
        } else {
            // 如果不存在，则添加新记录
            wrongQuestion.setWrongCount(1);
            wrongQuestionMapper.insert(wrongQuestion);
            return wrongQuestion;
        }
    }

    @Override
    public boolean updateWrongQuestion(WrongQuestion wrongQuestion) {
        return wrongQuestionMapper.update(wrongQuestion) > 0;
    }

    @Override
    public WrongQuestion getWrongQuestionById(int id) {
        return wrongQuestionMapper.selectById(id);
    }

    @Override
    public List<WrongQuestion> getWrongQuestionsByUserId(int userId) {
        return wrongQuestionMapper.selectByUserId(userId);
    }

    @Override
    public List<WrongQuestion> getWrongQuestionsByUserIdAndCategory(int userId, String category) {
        return wrongQuestionMapper.selectByUserIdAndCategory(userId, category);
    }

    @Override
    public WrongQuestion getWrongQuestionByUserAndQuestion(int userId, int questionId) {
        return wrongQuestionMapper.selectByUserIdAndQuestionId(userId, questionId);
    }

    @Override
    public boolean incrementWrongCount(int id) {
        WrongQuestion wrongQuestion = wrongQuestionMapper.selectById(id);
        if (wrongQuestion != null) {
            wrongQuestion.setWrongCount(wrongQuestion.getWrongCount() + 1);
            return wrongQuestionMapper.update(wrongQuestion) > 0;
        }
        return false;
    }
}
